package file.handling;

import engine.Edge;
import engine.Vertex;
import gui.Frame;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;

public class WriteFile
{
   private File file;
   private Frame frame;

   public WriteFile(File file, Frame frame)
   {
      this.frame = frame;
      this.file = file;
      write();
   }

   public void write()
   {
      String root = "NTP";
      Vertex v1, v2;
      Edge e;
      try
      {
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
         DocumentBuilder db = dbf.newDocumentBuilder();
         Document d = db.newDocument();
         org.w3c.dom.Element rootElement = d.createElement(root);
         d.appendChild(rootElement);

         for (int i = 0; i < frame.getView().getVertices().size(); i++)
         {
            v1 = frame.getView().getVertices().get(i);
            if(v1.getStatus()==1)
               v1.setStatus(0);
            org.w3c.dom.Element elem = d.createElement("Vertex");
            elem.setAttribute("name", v1.getName());
            elem.setAttribute("x", v1.getXtoString());
            elem.setAttribute("y", v1.getYtoString());
            elem.setAttribute("vstatus", "" + v1.getStatus());
            elem.setAttribute("Color_Node", v1.getColor().toString());
            rootElement.appendChild(elem);

         }

         for (int i = 0; i < frame.getView().getEdges().size(); i++)
         {
            e = frame.getView().getEdges().get(i);
            if(e.getStatus()==1)
               e.setStatus(0);
            v1 = e.getFirstNode();
            v2 = e.getSecondNode();
            org.w3c.dom.Element elem = d.createElement("Edge");
            elem.setAttribute("id1", ""+v1.getXtoString()+""+v1.getYtoString());
            elem.setAttribute("id2", v2.getuID());
            elem.setAttribute("weight", "" + e.getWeight());
            elem.setAttribute("estatus", "" + e.getStatus());
            elem.setAttribute("Color_Edge", e.getColor().toString());
            rootElement.appendChild(elem);
         }
         // File fxml = new File("test.xml");
         XMLUtil.write(d, file);

      }
      catch (IOException except)
      {
         // TODO Auto-generated catch block
         except.printStackTrace();
      }
      catch (ParserConfigurationException except)
      {
         // TODO Auto-generated catch block
         except.printStackTrace();
      }
   }
}
